package com.wanjia.estate.service.httpservice;

import cn.hutool.core.io.FileUtil;
import cn.hutool.json.JSONUtil;
import com.wanjia.estate.pojo.ocr.OcrResponse;
import com.wanjia.estate.properties.HttpRequestProperties;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Random;

@Slf4j
@Service
public class OcrHttpService extends AbstractHttpService {

    @Setter(onMethod_ = @Autowired)
    private HttpRequestProperties properties;

    public OcrResponse ocr(File file,String type) throws FileNotFoundException {
        Random rand = new Random();
        int randomNum = rand.nextInt(90000) + 10000;
        String str = Integer.toString(randomNum);//生成随机数

        String url = properties.getRemote().getOcrUrl()+"/"+type+"/"+str;
        log.debug("request url: {}", url);
        log.debug("request body: {}", file.getAbsolutePath());

        RequestEntity<byte[]> requestEntity = RequestEntity.post(url)
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .body(FileUtil.readBytes(file));
        ResponseEntity<String> entity = template.exchange(requestEntity, String.class);
        OcrResponse response = parseObjResponseEntity2(entity, OcrResponse.class);
        log.debug("response body: {}", JSONUtil.toJsonStr(response));

        return response;
    }


    public OcrResponse ocrScan(File file) throws FileNotFoundException {
        String url = properties.getRemote().getOcrsacnUrl();
        log.debug("request url: {}", url);
        log.debug("request body: {}", file.getAbsolutePath());

        RequestEntity<byte[]> requestEntity = RequestEntity.post(url)
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .body(FileUtil.readBytes(file));
        ResponseEntity<String> entity = template.exchange(requestEntity, String.class);
        OcrResponse response = parseObjResponseEntity2(entity, OcrResponse.class);
        log.debug("response body: {}", JSONUtil.toJsonStr(response));

        return response;
    }

}
